package upload

import (
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"go.uber.org/zap"
	"io"
	"math/rand"
	"mime/multipart"
	"os"
	"path"
	"time"
	"wave-service/server/app/common/utils"
	"wave-service/server/app/internal/config"
)

type Local struct{}

func (*Local) UploadFile(file *multipart.FileHeader, config config.Config) (string, error) {
	// 读取文件后缀
	ext := path.Ext(file.Filename)
	// 读取文件名并加密
	name := utils.Md5Encode(file.Filename + fmt.Sprintf("%d%04d", time.Now().Unix(), rand.Int31()))
	// 拼接新文件名
	filename := name + ext
	// 尝试创建此路径
	isPath, mkdirErr := utils.PathExists(config.Local.Path)
	if !isPath {
		os.MkdirAll(config.Local.Path, os.ModePerm)
	}
	if mkdirErr != nil {
		logx.Error("function os.MkdirAll() Filed", zap.Any("err", mkdirErr.Error()))
		return "", errors.New("function os.MkdirAll() Filed, err:" + mkdirErr.Error())
	}
	// 拼接路径和文件名
	filePath := config.Local.Path + "/" + filename

	f, openError := file.Open() // 读取文件
	if openError != nil {
		logx.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
		return "", errors.New("function file.Open() Filed, err:" + openError.Error())
	}
	defer f.Close() // 创建文件 defer 关闭

	out, createErr := os.Create(filePath)
	if createErr != nil {
		logx.Error("function os.Create() Filed", zap.Any("err", createErr.Error()))
		return "", errors.New("function os.Create() Filed, err:" + createErr.Error())
	}
	defer out.Close() // 创建文件 defer 关闭

	_, copyErr := io.Copy(out, f) // 传输（拷贝）文件
	if copyErr != nil {
		logx.Error("function io.Copy() Filed", zap.Any("err", copyErr.Error()))
		return "", errors.New("function io.Copy() Filed, err:" + copyErr.Error())
	}
	path := "/" + filePath

	return path, nil
}
